package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Myapplication;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.R;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.Constant;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.LogUtil;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.UserLocation;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.callback.LocationCallBack;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.service.TrailService;
import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.api.fence.CreateFenceRequest;
import com.baidu.trace.api.fence.CreateFenceResponse;
import com.baidu.trace.api.fence.DeleteFenceRequest;
import com.baidu.trace.api.fence.DeleteFenceResponse;
import com.baidu.trace.api.fence.FenceInfo;
import com.baidu.trace.api.fence.FenceListRequest;
import com.baidu.trace.api.fence.FenceListResponse;
import com.baidu.trace.api.fence.HistoryAlarmResponse;
import com.baidu.trace.api.fence.MonitoredStatus;
import com.baidu.trace.api.fence.MonitoredStatusByLocationRequest;
import com.baidu.trace.api.fence.MonitoredStatusByLocationResponse;
import com.baidu.trace.api.fence.MonitoredStatusInfo;
import com.baidu.trace.api.fence.MonitoredStatusRequest;
import com.baidu.trace.api.fence.MonitoredStatusResponse;
import com.baidu.trace.api.fence.OnFenceListener;
import com.baidu.trace.api.fence.UpdateFenceRequest;
import com.baidu.trace.api.fence.UpdateFenceResponse;
import com.baidu.trace.model.CoordType;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreateBaiduMapFenceActivity extends AppCompatActivity  implements LocationCallBack{
    @BindView(R.id.tb)
    Toolbar tb;
    @BindView(R.id.location_result)
    TextView result;
    private LBSTraceClient traceClient;
    private String fenceName;
    private long fenceIds;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_baidu_map_fence);
        ButterKnife.bind(this);
        initUI();
    }

    private void initUI() {
        Myapplication myapplication=(Myapplication) getApplication();
        traceClient=myapplication.client;
        //traceClient = new LBSTraceClient(getApplicationContext());
        setSupportActionBar(tb);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    int count=0;
    @OnClick({R.id.AddLocation,R.id.DeleteLocation,R.id.ChangeLocation,R.id.QueryAllLocation,R.id.whereMe})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.AddLocation:
                showDialog();
                //AddLocation();
                break;
            case R.id.DeleteLocation:
                DeleteLocation(count);
                count+=1;
                break;
            case R.id.ChangeLocation:
                ChangeLocation(2);
                break;
            case R.id.QueryAllLocation:
                QueryAllLocation();
                break;
            case R.id.whereMe:
                shoeMeLocation(fenceIds);
                break;
        }
    }

    private void shoeMeLocation(long fenceid) {

        // 请求标识
        int tag = 12;
        long serviceId = Constant.SERVICE_ID;
        String monitoredPerson = "13551240694";
        List<Long> fenceIds = new ArrayList<>();
        fenceIds.add(fenceid);
        com.baidu.trace.model.LatLng location = new com.baidu.trace.model.LatLng(30.538215230722, 104.06251881704);
        CoordType coordType = CoordType.bd09ll;

        // 创建查询服务端围栏指定位置上监控状态请求实例

        MonitoredStatusByLocationRequest request = MonitoredStatusByLocationRequest.buildServerRequest(tag,
                serviceId, monitoredPerson, fenceIds, location, coordType);
        //MonitoredStatusRequest monitoredStatusRequest=MonitoredStatusRequest.buildLocalRequest(tag,serviceId,monitoredPerson,fenceIds);
        traceClient.queryMonitoredStatusByLocation(request,onFenceListener);

        //traceClient.queryMonitoredStatus(monitoredStatusRequest,onFenceListener);
    }

    private void AddLocation() {

        if(fenceName.isEmpty()){
            return;
        }
        UserLocation instance = UserLocation.getUserLocationInstance();
        instance.getUserLocation(this,this);
        //CreateMapFence();
    }

    private void DeleteLocation(long... id ) {
        List<Long> list=new ArrayList();
        for (int i = 0; i < id.length; i++) {
            list.add(id[i]);
        }
        DeleteFenceRequest deleteFenceRequest=DeleteFenceRequest.buildLocalRequest(8,Constant.SERVICE_ID,"13551240694",list);
        traceClient.deleteFence(deleteFenceRequest,onFenceListener);
    }

    private void ChangeLocation(long fenceid) {
        int tag = 7;
        long serviceId = Constant.SERVICE_ID;
        String fenceName = "我的家";
        String monitoredPerson = "13551240694";
        double radius = 2000;// 围栏半径（单位 : 米）
        int denoise = 200;// 去噪精度
        CoordType coordType = CoordType.bd09ll;// 坐标类型
        // 围栏圆心
        com.baidu.trace.model.LatLng center = new com.baidu.trace.model.LatLng(31.538221902434, 101.06243823005);

        UpdateFenceRequest updateFenceRequest=UpdateFenceRequest.buildLocalCircleRequest(tag,
                serviceId,fenceid,fenceName, monitoredPerson, center, radius, denoise, coordType);
        traceClient.updateFence(updateFenceRequest,onFenceListener);

    }

    private void QueryAllLocation() {
        String monitoredPerson = "13551240694";
        FenceListRequest fenceListRequest= FenceListRequest.buildLocalRequest(9,Constant.SERVICE_ID,monitoredPerson,null);
        traceClient.queryFenceList(fenceListRequest,onFenceListener);
    }
    /*添加围栏*/

    private void CreateMapFence(double latitude, double longitude){
        int tag = 6;
        long serviceId = Constant.SERVICE_ID;
        String fenceName = this.fenceName;
        String monitoredPerson = "13551240694";
        double radius = 50;// 围栏半径（单位 : 米）
        int denoise = 200;// 去噪精度
        CoordType coordType = CoordType.bd09ll;// 坐标类型
        // 围栏圆心
        com.baidu.trace.model.LatLng center = new com.baidu.trace.model.LatLng(latitude, longitude);

        // 创建本地圆形围栏请求实例
        CreateFenceRequest localCircleFenceRequest = CreateFenceRequest.buildLocalCircleRequest(tag,
                serviceId,fenceName, monitoredPerson, center, radius, denoise, coordType);
        traceClient.createFence(localCircleFenceRequest,onFenceListener);
        //traceClient.deleteFence();
        //traceClient.updateFence();
        //traceClient.queryFenceList();

    }


     private OnFenceListener onFenceListener=new OnFenceListener() {
         @Override
         public void onCreateFenceCallback(CreateFenceResponse createFenceResponse) {
             String message = createFenceResponse.getMessage();
             String fenceName = createFenceResponse.getFenceName();
             int status = createFenceResponse.getStatus();
             Toast.makeText(CreateBaiduMapFenceActivity.this,"----"+status,Toast.LENGTH_SHORT).show();
             LogUtil.i("createinfo","----onCreateFenceCallback-----"+message+"-------fenceName--"+fenceName);

         }

         @Override
         public void onUpdateFenceCallback(UpdateFenceResponse updateFenceResponse) {
             String message = updateFenceResponse.getMessage();

             LogUtil.i("createinfo","----onUpdateFenceCallback-----"+message);
         }

         @Override
         public void onDeleteFenceCallback(DeleteFenceResponse deleteFenceResponse) {
             String message = deleteFenceResponse.getMessage();
             LogUtil.i("createinfo","----onDeleteFenceCallback-----"+message);
         }

         @Override
         public void onFenceListCallback(FenceListResponse fenceListResponse) {
             List<FenceInfo> fenceInfos = fenceListResponse.getFenceInfos();
             int size = fenceListResponse.getSize();
             StringBuffer buffer=new StringBuffer();
             buffer.append(" 共计："+size+"条 \n");
             if(size >0){
                 fenceIds = fenceInfos.get(0).getCircleFence().getFenceId();
             }
             for (FenceInfo fencein :fenceInfos) {
                 String FenceName = fencein.getCircleFence().getFenceName();
                 long fenceId = fencein.getCircleFence().getFenceId();
                 buffer.append(" 编号："+fenceId+"     名称："+FenceName+"\n");
             }
             result.setText(buffer);

         }

         @Override
         public void onMonitoredStatusCallback(MonitoredStatusResponse monitoredStatusResponse) {
             String message = monitoredStatusResponse.getMessage();
             LogUtil.i("createinfo","----onMonitoredStatusCallback-----"+message);
             List<MonitoredStatusInfo> statusInfos = monitoredStatusResponse.getMonitoredStatusInfos();

             LogUtil.i("createinfo","----onMonitoredStatusCallback-----"+statusInfos.size()+"------");
             StringBuffer buffer = new StringBuffer();

             for (MonitoredStatusInfo mon:statusInfos) {
                 MonitoredStatus status = mon.getMonitoredStatus();
                 switch (status){
                     case in:
                         buffer.append("您在围栏里边哦 \n");
                         break;
                     case out:
                         buffer.append("您在围栏外边哦 \n");
                         break;
                     case unknown:
                         buffer.append("您的位置我不知道呢 \n");
                         break;
                 }
             }
             result.setText(buffer);

         }

         @Override
         public void onMonitoredStatusByLocationCallback(MonitoredStatusByLocationResponse monitoredStatusByLocationResponse) {

             String message = monitoredStatusByLocationResponse.getMessage();
             LogUtil.i("createinfo","----onMonitoredStatusByLocationCallback-----"+message);
             List<MonitoredStatusInfo> statusInfos = monitoredStatusByLocationResponse.getMonitoredStatusInfos();
             LogUtil.i("createinfo","----onMonitoredStatusByLocationCallback-----"+statusInfos.size());
             for (MonitoredStatusInfo mon:statusInfos) {
                 MonitoredStatus status = mon.getMonitoredStatus();
                 switch (status){
                     case in:
                         result.setText("您在围栏里边哦");
                         break;
                     case out:
                         result.setText("您在围栏外边哦");
                         break;
                     case unknown:
                         result.setText("您的位置我不知道呢");
                         break;
                 }
             }



         }

         @Override
         public void onHistoryAlarmCallback(HistoryAlarmResponse historyAlarmResponse) {
             String message = historyAlarmResponse.getMessage();
             LogUtil.i("createinfo","----onHistoryAlarmCallback-----"+message);


         }
     };

     private void showDialog(){
         final EditText editText = new EditText(this);
         new AlertDialog.Builder(this)
                 .setTitle("请输入名称")
                 .setView(editText)
                 .setNegativeButton("取消",null)
                 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         fenceName = editText.getText().toString();
                         if(fenceName.isEmpty()){
                             Toast.makeText(CreateBaiduMapFenceActivity.this,"名字不能为空",Toast.LENGTH_SHORT).show();
                             return;
                         }
                         dialog.dismiss();
                         AddLocation();
                     }
                 })
                 .create()
                 .show();
     }

    @Override
    public void getUserLocation(BDLocation location) {
        String address = location.getAddrStr();
        LogUtil.i("createinfo","-------"+address);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        CreateMapFence(latitude,longitude);

    }

    @Override
    public void getUserCoordinate(double latitude, double longitude) {

    }
}
